/*
 * MageLordServlet.java
 * Copyright 2012 Erik Strelzoff
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.magelord.servlet;

import com.google.gson.Gson;
import com.magelord.utils.Logger;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MageLordServlet extends HttpServlet {
	
	private MageLordServletContext m_context = null;
	private ServletConfig m_servletConfig = null;
	
	private RequestHandlerFactory m_handlerFactory = null;
	
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		
		m_context = new MageLordServletContext(getServletContext());
		m_servletConfig = getServletConfig();
		m_handlerFactory = new RequestHandlerFactory(m_context);
		Logger.setContext(m_context);
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String req = request.getParameter("request");
		
		m_context.log("MageLordServlet received request: '" + req + "'");
		
		if (req == null || req.length() == 0) {
			// No request.  Default debug or nothing if we're not in debug mode.
			writeJSON(m_context.makeJSONError("MageLordServlet:  No request"), response);
			return;			
		}
		
		RequestHandler handler = m_handlerFactory.getRequestHandler(req);
		if (handler == null) {
			// Error
			writeJSON(m_context.makeJSONError("MageLordServlet:  Unknown request: " + req), response);
			return;
		}
		
		// Handle the request.
		writeJSON(handler.handleRequest(request.getParameterMap()), response);
	}
	
	public void writeJSON(Object jobj, HttpServletResponse response) throws IOException {
		Gson gson = m_context.getGson();
		String jsonText = gson.toJson(jobj);
		response.setContentType("text/json");
		response.setContentLength(jsonText.length());

		PrintWriter out = response.getWriter();
		out.print(jsonText);
		out.flush();
	}
}